var currentAccountUnit;
var accountStore = new Ext.data.Store({
			proxy : new Ext.data.HttpProxy({
				url : 'authorize.action?method=findUserByUnit',
				method:'GET'
			}),
			reader : new Ext.data.JsonReader({
				id : 'id',
				root : 'data',
				totalProperty : 'totalProperty',
				fields : [
					{name : 'id',mapping : 'id'},
					{name : 'loginName', mapping : 'loginName'},
					{name : 'userName', mapping : 'userName'},
					{name : 'email', mapping : 'email'},
					{name : 'phone', mapping : 'phone'},
					{name : 'mobilePhone', mapping : 'mobilePhone'}
				]
			})
		});

accountGrid = new Ext.grid.GridPanel({
		id : 'accountTab',
		title : '单位用户',
    	height:Ext.get("content").getHeight(),
    	viewConfig:{forceFit:true},//自动填充列宽.
    	store : accountStore,
    	cm : new Ext.grid.ColumnModel([
			new Ext.grid.CheckboxSelectionModel(),
			new Ext.grid.RowNumberer({header:'行号',width:40}),
	        {header: '账号', dataIndex: 'loginName', width: 100, sortable : true},
	        {header: '姓名', dataIndex: 'userName', width: 100},   
	        {header: '电子邮件', dataIndex: 'email', width: 100},
	        {header: '电话', dataIndex: 'phone',width : 100},
	        {header: '手机', dataIndex: 'mobilePhone',width : 100}
	    ]),
    	trackMouseOver : false,
    	sm : new Ext.grid.CheckboxSelectionModel(),
    	tbar : new Ext.Toolbar([
	    	{text:'添加账户',icon:'icons/toolBar/add.gif',handler:addUser},
	    	{text:'修改账户',icon:'icons/toolBar/plugin.gif',handler:modifyUser},
	    	{text:'删除账户',icon:'icons/toolBar/delete.gif',handler:delUser},
	    	{text:'授权',icon:'icons/toolBar/add.gif',handler:show_account_role_win}
	    ]),
	    bbar: new Ext.PagingToolbar({
	            pageSize: 10,      
	            store: accountStore,
	            displayInfo: true,
	            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
	            emptyMsg: "没有记录"
	        }),
	    listeners: {activate: accountHandleActivate}
    });
 
function accountHandleActivate(){
	//得到当前选中的单位，加载数据.
	if(currentUnit != null && currentAccountUnit != currentUnit){
		var unitId = currentUnit.attributes.id;
		if(unitId != null && unitId != ''){
			currentAccountUnit = currentUnit;
			accountStore.load({params:{'unitId':unitId}});
		}
	}//
}



Ext.form.Field.prototype.msgTarget = 'side';
var userForm = new Ext.FormPanel({
	labelSeparator : ':',
	frame : true,
	border:false,
	items:[
		{
			xtype:'textfield',
			width:200,
			allowBlank:false,
			blankText : '账号不能为空',
			name:'loginName',
			fieldLabel : '登陆账号'
		},{
			xtype:'textfield',
			width:200,
			allowBlank:false,
			blankText : '密码不能为空',
			name:'loginPasswd',
			fieldLabel : '登陆密码'
		},{
			xtype:'textfield',
			width:200,
			allowBlank:false,
			blankText : '姓名不能为空',
			name:'userName',
			fieldLabel : '姓名'
		},{
			xtype:'textfield',
			width:200,
			name:'mobilePhone',
			fieldLabel : '移动电话'
		},{
			xtype:'textfield',
			width:200,
			name:'phone',
			fieldLabel : '电话'
		},{
			xtype:'textfield',
			width:200,
			name:'email',
			fieldLabel : 'email'
		},{
			xtype:'textfield',
			width:200,
			name:'fax',
			fieldLabel : '传真'
		},{
			xtype:'hidden',
			name:'groupId'
		},{
			xtype:'hidden',
			name:'groupCode'
		},{
			xtype:'hidden',
			name : 'id'
		}
	],
	buttons:[
		{
			text : '关闭',
			handler : function(){
				userFormWin.hide();
			}
		},{
			text : '提交',
			handler : submitUserForm
		}
	]
});

var userFormWin = new Ext.Window({
		layout:'fit',
		width:380,
		height:400,
		closeAction:'hide',
		resizable:false,//true可以拖动大小.
		shadow : true,//投影效果.
		modal:true,//对后面内容进行遮盖.
		closable:true,
		bodyStyle:'padding:5 5 5 5',
		animCollapse:true,//关闭面板是的动画效果.
		items:[userForm]
});

function submitUserForm(){
	var postUrl;
	if(userForm.isAdd){
		postUrl = 'authorize.action?method=addUser'
	}else{
		postUrl = 'authorize.action?method=modifyUser'
	}
	userForm.getForm().submit({
			clientValidation:true,
    		waitMsg:'正在执行操作',
    		waitTitle:'提示',
    		url:postUrl,
    		method:'POST',
    		success:function(form,action){
    			userFormWin.hide();
    			accountStore.reload();
    			Ext.Msg.alert('提示','操作成功');
    		},
    		failure:function(form,action){
    			Ext.Msg.alert('提示','操作失败');
    		}
		});
}

function addUser(){
	if(currentUnit){
		userForm.getForm().reset();
		userForm.isAdd = true;
		userForm.getForm().setValues({groupId:currentUnit.attributes.id,groupCode:currentUnit.attributes.code});
		userFormWin.setTitle('添加用户----'+currentUnit.attributes.text);
		userFormWin.show();
	}else{
		Ext.Msg.alert('提示','请选择用户所在单位!')
	}
}

function modifyUser(){
	var ids = []; 
	ids = getSelectedUser();
	if(ids.length > 1){
		Ext.Msg.alert('提示','只能修改一名帐户!');
	}else if(!ids){
		Ext.Msg.alert('提示','请选择要修改的帐户!');
	}else{
		userForm.getForm().reset();
		userForm.isAdd = false;
		var id = ids[0];
		loadUserForm(id);
		userFormWin.setTitle('修改帐户');
		userFormWin.show();
	}
}

function delUser(){
	var ids = []; 
	ids = getSelectedUser();
	if(!ids){
		Ext.Msg.alert('提示','请选择要删除的项目');
	}else{
		Ext.MessageBox.confirm('提示','您确定要删除选定的账户吗?',
    		function(btnId){
    			if(btnId == 'yes'){
    				deleteUser(ids);
    			}
    		}
    	);
	}
}

function deleteUser(ids){
	var userDeleteTip = Ext.MessageBox.show({
		msg: '正在删除所选项目, 稍后...',
        progressText: '删除...',
        width:300,
        wait:true,
        waitConfig: {interval:200}
	});
	
	Ext.Ajax.request({
				url : 'authorize.action?method=deleteUser',
				params : {'ids' : ids},
				method : 'POST',
				success : function(response, options) {
					userDeleteTip.hide();
					var result = Ext.util.JSON.decode(response.responseText);
					if (result.success) {
						for (var i = 0; i < ids.length; i++) {
							var index = accountStore.find('id', ids[i]);
							if (index != -1) {
								var rec = accountStore.getAt(index);
								accountStore.remove(rec);
							}
						}
						Ext.Msg.alert('提示', '成功删除项目');
					}
				},
				failure : function(response, options) {
					userDeleteTip.hide();
					Ext.Msg.alert('提示', '删除失败.');
				}
			});
}

function loadUserForm(userId){
	userForm.getForm().load({
		waitMsg : '正在加载数据',
		waitTitle : '提示',
		url : 'authorize.action?method=loadUser',
		params : {'id':userId},
		method : 'GET',
		success : function(form,action){
			//数据加载成功.	
		},
		failure : function(form,action){
			Ext.Msg.alert('无法加载该数据');
		}
	});
}


function getSelectedUser(){
    	var selectedUser = accountGrid.getSelectionModel().getSelections();
    	var idList = [];
    	if(selectedUser.length == 0){
    		return false;
    	}else{
    		for(var i=0; i<selectedUser.length; i++){
    			idList.push(selectedUser[i].get('id'));
    		}
    	}
    	return idList;
    }


//======================== 添加角色 =====================
    
var account_role_Store = new Ext.data.Store({
			proxy : new Ext.data.HttpProxy({
				url : 'authorize.action?method=getAccountRole',
				//url : 'data.json',
				method:'GET'
			}),
			reader : new Ext.data.JsonReader({
				id : 'id',
				root : 'data',
				totalProperty : 'totalProperty',
				fields : [
					{name : 'id',mapping : 'id'},
					{name : 'name', mapping : 'name'},
					{name : 'status', mapping : 'status'},
					{name : 'checked', mapping : 'checked'}
				]
			})
		});
		
var account_role_Grid = new Ext.grid.GridPanel({
    	viewConfig:{forceFit:true},//自动填充列宽.
    	store : account_role_Store,
    	cm : new Ext.grid.ColumnModel([
			new Ext.grid.CheckboxSelectionModel(),
			new Ext.grid.RowNumberer({header:'行号',width:40}),
	        {header: '角色名称', dataIndex: 'name', width: 100, sortable : true},
	        {header: '状态', dataIndex: 'status', width: 100} 
	    ]),
    	trackMouseOver : false,
    	sm : new Ext.grid.CheckboxSelectionModel(),
    	bbar : new Ext.Toolbar([
	    	{text:'确定',icon:'icons/toolBar/add.gif',handler:add_role_To_account}
	    ])
    });
    
	account_role_Store.on(
		'load',
		function(store,records,options){
			var array = [];
			for(var i=0; i<records.length; i++){
				var record
				record = records[i];
				if(record.get('checked')== true){
					array.push(record);
				}
			}
			account_role_Grid.getSelectionModel().selectRecords(array);
		},
		this,
		{delay:100}
	);

var roleGridWin = new Ext.Window({
	layout:'fit',
	width:400,
	height:450,
	closeAction:'hide',
	resizable:false,//true可以拖动大小.
	shadow : true,//投影效果.
	modal:true,//对后面内容进行遮盖.
	closable:true,
	bodyStyle:'padding:5 5 5 5',
	animCollapse:true,//关闭面板是的动画效果.
	items:[account_role_Grid]
});


function show_account_role_win(){
	account_role_Store.removeAll();
	var userIdArray = [];
	userIdArray = getSelectedUser();
	if(userIdArray.length > 1){
		account_role_Store.load();
	}else if(userIdArray.length == 1){
		account_role_Store.load({params:{'accountId':userIdArray[0]}});
	}else{
		Ext.Msg.alert('提示','请选择账户进行操作!');
		return;
	}
	roleGridWin.setTitle('授予角色');
	roleGridWin.show();
}

function add_role_To_account(){
	var role_records = [];
	var role_ids = [];
	role_records = account_role_Grid.getSelectionModel().getSelections();
	for(var i=0; i<role_records.length; i++){
		role_ids.push(role_records[i].get('id'));
	}
	
	var account_ids = [];
	account_ids = getSelectedUser();
	
	var authorizeTip = Ext.MessageBox.show({
		msg: '正在进行授权, 稍后...',
        progressText: '授权...',
        width:300,
        wait:true,
        waitConfig: {interval:200}
	});
	
	Ext.Ajax.request({
				url : 'authorize.action?method=authorizeAccount',
				params : {'accountIds' : account_ids,'roleIds' : role_ids},
				method : 'POST',
				success : function(response, options) {
					authorizeTip.hide();
					roleGridWin.hide();
					var result = Ext.util.JSON.decode(response.responseText);
					if (result.success) {
						Ext.Msg.alert('提示', '授权成功!');
					}else{
						Ext.Msg.alert('提示', '授权失败!');
					}
				},
				failure : function(response, options) {
					roleGridWin.hide();
					Ext.Msg.alert('提示', '授权失败!');
				}
			});
}